package org.example.utils;

import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;
import org.example.config.PropertiesConfig;

import java.util.Calendar;
import java.util.Date;
import java.util.Map;

// token工具
@Slf4j
public class JwtUtil {

    private static String key = PropertiesConfig.getKey();
    private static Integer time = PropertiesConfig.getTime();

    public static String createToken(Map<String, String> map) {

        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.SECOND, time);

        JwtBuilder jwtBuilder = Jwts.builder()
                .signWith(SignatureAlgorithm.HS256, key);
        map.forEach((key, value) -> {
            jwtBuilder.claim(key, value);
        });
        // 设置 签名时间, 过期时间
        String token = jwtBuilder.setIssuedAt(new Date())
                .setExpiration(calendar.getTime()).compact();

        return token;
    }

    public static String createToken(Long id, String account, String permissions) {

        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.SECOND, time);
        log.info("有效时间: {}",time);
        JwtBuilder jwtBuilder = Jwts.builder()
                .signWith(SignatureAlgorithm.HS256, key);
        jwtBuilder.setId(String.valueOf(id));
        jwtBuilder.setSubject(account);
        jwtBuilder.claim("permissions",permissions);
        // 设置 签名时间, 过期时间
        String token = jwtBuilder.setIssuedAt(new Date())
                .setExpiration(calendar.getTime()).compact();

        return token;
    }

    public static Claims decryptToken(String token) {
        try {
            Claims claims = Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody();
            return claims;
        } catch (Exception e) {
            log.info("解析token失败");
            return null; // 解密失败则返回null
        }

    }

}

